﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OnlineCourse.JWTAuthorizePolicy;
using OnlineCourse.Model;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using OnlineCourse.Model.Entity;

namespace OnlineCourse.API.Controllers
{
   // [Authorize("Permission")]
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {

        private readonly PermissionRequirement _requirement;
        private readonly Services.UserService _usbll;

        
        public UserController(ApplicationDbContext db, PermissionRequirement requirement)
        {

            _requirement = requirement;
            _usbll = new Services.UserService(db);
        }
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("Authorize")]
        public async Task<IActionResult> Authorize(string username, string password)
        {
            var pw = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(password))).Replace("-", "");
            Model.Entity.User user = null;

            await Task.Run(() =>
            {
                user = _usbll.GetByLogin(username, pw);
            });

            if (user == null)
            {
                return Ok(new
                {
                    Code = "401",
                    Message = "用户登录失败"
                });
            }
            else
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim("Id",user.Id.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())//过期时间
                };
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);

                var token = JwtToken.BuildJwtToken(claims, _requirement);
                return Ok(token);
            }
        }
        [AllowAnonymous]
        [HttpPost("Add")]
        public IActionResult Add(string Name,string pwd, string Sex, int Age)
        {
            var a = _usbll.Add(Name,pwd, Sex, Age);
            return Ok(a);
        }
    }
}